<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.name" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search" icon="el-icon-search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd" icon="el-icon-plus">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="dics" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      
      <el-table-column prop="name" label="字典名称" width="380" sortable>
      </el-table-column>
      
      <el-table-column prop="types.sn" label="字典类型" width="450" sortable>
      </el-table-column>
      
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)" class="el-icon-edit">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)" class="el-icon-delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <!-- 为批量删除按钮绑定事件，当sels的长度大于零时，触发事件 -->
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
      </el-pagination>
    </el-col>

    <!-- 编辑界面  :visible.sync 控制当前窗体是否显示  :rules  表单校验引用规则  ref=  给当前表单取一个引用别名 -->
    <el-dialog :title="title" :visible.sync="dicFormVisible" :close-on-click-modal="false">
      <el-form :model="dicForm" label-width="80px" :rules="dicFormRules" ref="dicForm">
        <!--prop="name"  申明表单中有一个属性name-->
        
        <el-form-item label="字典名称" prop="name">
          <el-input v-model="dicForm.name" auto-complete="off"></el-input>
        </el-form-item>
        
        <el-form-item label="字典类型">
          <!--<el-input v-model="dicForm.types" auto-complete="off"></el-input>-->
          <el-select v-model="dicForm.types" clearable value-key="id" placeholder="请选择">
            <!--
               clearable  可清空
               <el-option  : 选择项
               :label 选择后展示在选择框中的内容
               :value 选择后你要传送给后端的值
            -->
            <el-option
                v-for="item in dictypes"
                :key="item.id"
                :label="item.sn"
                :value="item">
              <span style="float: left">{{ item.sn }}</span>
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="dicFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="dicSubmit" :loading="dicLoading">提交</el-button>
      </div>
    </el-dialog>


  </section>
</template>

<script>

export default {
  data() {
    return {
      filters: {
        name: ''
      },
      dicTree: [],
      dics: [],
      dictypes: [],
      currentPage: 1,
      total: 0,
      pageSize: 10,
      title:'',
      listLoading: false,
      sels: [], // 列表选中列
      dicFormVisible: false,// 编辑界面是否显示
      dicLoading: false,
      dicFormRules: {// 申明表单中属性的校验规则
        name: [
          {required: true, message: '请输入姓名吧', trigger: 'blur'}
        ],
        sn: [
          {required: true, message: '请输入编号吧', trigger: 'blur'}
        ]
      },
      // 编辑界面数据
      dicForm: {
        id: null,
        name: "",
        sn: "",
        state: 0,
        types: "",
        parent: null
      },

    }
  },

  /* methods 方法头部*/
  methods: {
    search(){
      this.currentPage = 1;
      this.getDics();
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getDics();
    },
    // 获取部门列表
    getDics() {
      let para = {
        currentPage: this.currentPage,
        name: this.filters.name,
        pageSize:this.pageSize
      };
      this.listLoading = true;// 开启忙等框
      this.$http.post("/dic", para)// 请求地址：后台的dic接口
          .then(result => {
            result = result.data;// 将列表数据PageList{total rows}赋值给result
            this.dics = result.rows;

            this.listLoading = false;// 关闭忙等框
            this.total = result.total;
          })
          .catch(result => {
            console.log(result);
            alert("系统快爆炸了！");
          })
    },
    // 删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '强制提醒', {// 弹出删除提示框
        type: 'warning'
      }).then(() => {// 如果成功，则执行以下操作
        this.listLoading = true;// 打开忙等框
        let para = {id: row.id};// 获取当前行的id
        this.$http.delete("/dic/" + row.id)// 发起axios请求
            .then(result => {// 如果成功，则提示用户
              this.listLoading = false;// 关闭忙等框
              if (result.data.success) {
                this.$message({
                  message: "删除成功",
                  type: "success"
                })
              } else {
                this.$message({
                  message: "删除失败",
                  type: "error"
                })
              }
              this.currentPage = 1;// 删除成功后再定位到第一页
              this.getDics();// 重新刷新列表

            }).catch(result => {// 不成功则发送错误信息提醒用户
          this.listLoading = false;// 关闭忙等框
          this.$message({
            message: "删除失败",
            type: "error"
          })
        })

      }).catch(() => {// 如果用户点击取消，则不执行任何操作

      });
    },
    // 显示编辑界面
    handleEdit: function (index, row) {
      this.getDeptTree();
      this.title = "修改";
      this.dicFormVisible = true;
      this.dicForm = Object.assign({}, row);// 克隆一份当前列数据做回显
      let dirPath = row.dirPath;// 获取当前列的层级目录
      if (dirPath) {// 判断，如果dirPath不等于空的话
        let array = dirPath.split("/");// 就通过/分割
        let parent = [];// 申明一个空数组赋值给父节点
        for (let i = 1; i < array.length - 1; i++) {// 从下标1开始遍历分割后获得的数组，
          parent.push(parseInt(array[i]));// 将遍历后的值转换为整数后添加到父节点
        }
        this.dicForm.parent = parent;
      }
    },

    // 显示新增界面
    handleAdd: function () {
      this.getDeptTree();
      this.dicFormVisible = true;
      this.title = "添加",
          this.dicForm = {// 显示表单时先清空表单
            id: null,
            name: "",
            sn: "",
            state: 0,
            types: "",
            parent: null
          };
    },
    // 提交表单
    dicSubmit: function () {
      // validate开启表单校验
      this.$refs.dicForm.validate((valid) => {
        if (valid) {// 如果校验通过，执行下面操作
          this.$confirm('确认提交吗？', '强制提示', {}).then(() => {
            this.dicLoading = true;// 开启忙等框
            let para = Object.assign({}, this.dicForm);// 复制表单数据
            if (para.parent) {
              let parent = para.parent;
              let pid = parent[parent.length - 1];
              para.parent = {"id": pid};
            }
            this.$http.put("/dic", para)
                .then(result => {
                  result = result.data;
                  this.dicLoading = false;// 关闭忙等框
                  this.dicFormVisible = false;// 关闭模态框
                  if (result.success) {
                    this.$message({
                      message: "操作成功！",
                      type: "success"
                    });
                  } else {
                    this.$message({
                      message: "操作失败！！",
                      type: "error"
                    });
                  }

                  this.page = 1;// 跳转到第一页
                  this.getDics();// 重新刷新页面
                })
                .catch(result => {
                  this.dicLoading = false;
                  this.$message({
                    message: "操作失败",
                    type: "error"
                  })
                })


          });
        }
      });


    },


    selsChange: function (sels) {// 封装被选中的对象
      this.sels = sels;
      console.log(this.sels)
    },
    // 批量删除，
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '强制提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;// 打开忙等框
        this.$http.patch("/dic/", ids)
            .then(result => {// 如果成功，就走这里
              result = result.data;
              if (result.success) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
              } else {
                this.$message({
                  message: '删除失败',
                  type: 'error'
                });
              }
              this.currentPage = 1;// 删除成功后再定位到第一页
              this.getDics();// 重新刷新列表
            })
            .catch(result => {
              alert("系统错误")
            })
            .catch(result => {// 不成功，就没动作
            })
      }).catch(() => {
      });
    },
    // 获取员工列表数据
    getTypes(){
      this.$http.get("/dictype")
          .then(result => {
            result = result.data;
            this.dictypes = result
          })
          .catch(result => {
          })
    },

    getDeptTree(){// 获取部门级联树
      this.$http.get("/dic/tree")
          .then(result => {
            result = result.data;
            this.dicTree = result;
          })
    }




  },
  /* methods 方法尾部*/

  mounted() {
    this.getDics();// 页面加载完毕后立即加载部门和员工列表
    this.getTypes();
  }
}

</script>

<style scoped>

</style>
